package com.maktoub.project.controller;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.maktoub.apiclientstart.client.ApiInterfaceClient;
import com.maktoub.common.model.entity.InterfaceInfo;
import com.maktoub.common.model.entity.User;
import com.maktoub.common.model.entity.UserInterfaceInfo;
import com.maktoub.project.annotation.AuthCheck;
import com.maktoub.project.common.BaseResponse;
import com.maktoub.project.common.ErrorCode;
import com.maktoub.project.common.IdRequest;
import com.maktoub.project.common.ResultUtils;
import com.maktoub.project.exception.BusinessException;
import com.maktoub.project.model.dto.applyinterfaceinfo.ApplyInterfaceInfoAddRequest;
import com.maktoub.project.model.dto.applyinterfaceinfo.ApplyInterfaceInfoQueryForAdminRequest;
import com.maktoub.project.model.dto.applyinterfaceinfo.ApplyInterfaceInfoQueryRequest;
import com.maktoub.project.model.dto.applyinterfaceinfo.ApplyInterfaceInfoUpdateRequest;
import com.maktoub.project.model.entity.ApplyInterfaceInfo;
import com.maktoub.project.model.vo.ApplyInterfaceComplexVO;
import com.maktoub.project.model.vo.ApplyInterfaceInfoVO;
import com.maktoub.project.service.ApplyInterfaceInfoService;
import com.maktoub.project.service.InterfaceInfoService;
import com.maktoub.project.service.UserInterfaceInfoService;
import com.maktoub.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 帖子接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/applyInterfaceInfo")
@Slf4j
public class ApplyInterfaceInfoController {

    @Resource
    private ApplyInterfaceInfoService applyInterfaceInfoService;

    @Autowired
    ApiInterfaceClient apiInterfaceClient;
    @Autowired
    InterfaceInfoService interfaceInfoService;

    @Autowired
    UserInterfaceInfoService userInterfaceInfoService;
    //    ApiInterfaceClient tempapiInterfaceClient1;
    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param applyInterfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addApplyInterfaceInfo(@RequestBody ApplyInterfaceInfoAddRequest applyInterfaceInfoAddRequest,
                                                    HttpServletRequest request) {
        if (applyInterfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        ApplyInterfaceInfo applyInterfaceInfo = new ApplyInterfaceInfo();
        BeanUtils.copyProperties(applyInterfaceInfoAddRequest, applyInterfaceInfo);
        User loginUser = userService.getLoginUser(request);
        applyInterfaceInfo.setUserId(loginUser.getId());
        // 校验,添加，与其他校验传入得参数就是一个add不一样
        applyInterfaceInfoService.validInterfaceInfo(applyInterfaceInfo, true);

        //如果该接口已经申请呢？，也是一条提交记录

        boolean result = applyInterfaceInfoService.save(applyInterfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = applyInterfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = "admin")
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> deleteApplyInterfaceInfo(@RequestBody List<IdRequest> idRequest, HttpServletRequest request) {

        if (idRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        int i = 0;
        for (IdRequest item : idRequest) {
            long id = item.getId();
            // 判断是否存在
            ApplyInterfaceInfo oldInterfaceInfo = applyInterfaceInfoService.getById(id);
            if (oldInterfaceInfo == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
            // 仅本人或管理员可删除
            if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            boolean b = applyInterfaceInfoService.removeById(id);
        }

        return ResultUtils.success(true);
    }


    /**
     * 更新
     *
     * @param applyInterfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateApplyInterfaceInfo(@RequestBody ApplyInterfaceInfoUpdateRequest applyInterfaceInfoUpdateRequest,
                                                          HttpServletRequest request) {
        if (applyInterfaceInfoUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        ApplyInterfaceInfo applyInterfaceInfo = new ApplyInterfaceInfo();
        BeanUtils.copyProperties(applyInterfaceInfoUpdateRequest, applyInterfaceInfo);

        //为了复用接口方法，所以用InterfaceInfo,也为了用户传不改传的参数
        // 参数校验
        applyInterfaceInfoService.validInterfaceInfo(applyInterfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = applyInterfaceInfoUpdateRequest.getId();
        // 判断是否存在
        ApplyInterfaceInfo oldApplyInterfaceInfo = applyInterfaceInfoService.getById(id);
        if (oldApplyInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 对应的接口的userId没传进来

        // 仅本人或管理员可修改
        if (!(oldApplyInterfaceInfo.getUserId().equals(user.getId())) && !(userService.isAdmin(request))) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        applyInterfaceInfo.setUpdateTime(DateTime.now());
        boolean result = applyInterfaceInfoService.updateById(applyInterfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<ApplyInterfaceInfo> getApplyInterfaceInfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ApplyInterfaceInfo applyInterfaceInfo = applyInterfaceInfoService.getById(id);
        return ResultUtils.success(applyInterfaceInfo);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param applyInterfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<ApplyInterfaceInfo>> listApplyInterfaceInfo(ApplyInterfaceInfoQueryRequest applyInterfaceInfoQueryRequest) {
        ApplyInterfaceInfo applyInterfaceInfoQuery = new ApplyInterfaceInfo();
        if (applyInterfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(applyInterfaceInfoQueryRequest, applyInterfaceInfoQuery);
        }
        QueryWrapper<ApplyInterfaceInfo> queryWrapper = new QueryWrapper<>(applyInterfaceInfoQuery);
        List<ApplyInterfaceInfo> interfaceInfoList = applyInterfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取列表
     *
     * @param applyInterfaceInfoQuery
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<ApplyInterfaceInfoVO>> listApplyInterfaceInfoByPage(
            ApplyInterfaceInfoQueryRequest applyInterfaceInfoQuery) {


        if (applyInterfaceInfoQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = applyInterfaceInfoQuery.getCurrent();
        long size = applyInterfaceInfoQuery.getPageSize();
        String sortField = applyInterfaceInfoQuery.getSortField();
        String sortOrder = applyInterfaceInfoQuery.getSortOrder();


        // description 需支持模糊搜索,为什么需要set NULL,因为后面wrapper传进去如果有值，like就不生效了
//        interfaceInfoQuery.setDescription(null);

        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //描述信息检索
        Long userId = applyInterfaceInfoQuery.getUserId();
        Long interfaceId = applyInterfaceInfoQuery.getInterfaceId();
        Long applyNum = applyInterfaceInfoQuery.getApplyNum();
        Integer status = applyInterfaceInfoQuery.getStatus();
        String payerName = applyInterfaceInfoQuery.getPayerName();

        //and的关系
        LambdaQueryWrapper<ApplyInterfaceInfo> queryWrapper = new LambdaQueryWrapper<ApplyInterfaceInfo>()
                .like(userId != null && userId > 0, ApplyInterfaceInfo::getUserId, userId)
                .like(interfaceId != null && interfaceId > 0, ApplyInterfaceInfo::getInterfaceId, interfaceId)
                .like(applyNum != null && applyNum > 0, ApplyInterfaceInfo::getApplyNum, applyNum)
                .like(status != null, ApplyInterfaceInfo::getStatus, status)
                .like(StringUtils.isNotBlank(payerName), ApplyInterfaceInfo::getPayerName, payerName);

        Page<ApplyInterfaceInfo> interfaceInfoPage = applyInterfaceInfoService.page(new Page<>(current, size), queryWrapper);
        // 获取记录列表
        List<ApplyInterfaceInfo> records = interfaceInfoPage.getRecords();

        // 遍历记录列表,得到接口名
        ArrayList<String> interfaceInfosNames = new ArrayList<>();
        for (ApplyInterfaceInfo info : records) {
            // 在这里处理每个 ApplyInterfaceInfo 对象
            InterfaceInfo byId = interfaceInfoService.getById(info.getInterfaceId());
            interfaceInfosNames.add(byId.getName());
        }

        ApplyInterfaceInfoVO applyInterfaceInfoVO = new ApplyInterfaceInfoVO();
        List<ApplyInterfaceInfoVO> combinedList = new ArrayList<>();
        int minSize = Math.min(records.size(), interfaceInfosNames.size());

        for (int i = 0; i < minSize; i++) {
            String interfaceName = interfaceInfosNames.get(i);
            ApplyInterfaceInfo info = records.get(i);
            ApplyInterfaceInfoVO vo = new ApplyInterfaceInfoVO();
            vo.setStatus(info.getStatus());
            vo.setPayerName(info.getPayerName());
            vo.setInterfaceName(interfaceName);
            vo.setCreateTime(info.getCreateTime());
            vo.setUpdateTime(info.getUpdateTime());
            combinedList.add(vo);
        }
        Page<ApplyInterfaceInfoVO> voPage = new Page<>(current, size);
        voPage.setRecords(combinedList);
        voPage.setTotal(interfaceInfoPage.getTotal());
        voPage.setCurrent(interfaceInfoPage.getCurrent());
        voPage.setSize(interfaceInfoPage.getSize());
        voPage.setPages(interfaceInfoPage.getPages());
        return ResultUtils.success(voPage);
    }

    //任务数量,管理员处理
    @GetMapping("/list/page/complex_mes")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<ApplyInterfaceComplexVO> listApplyInterfaceInfoCountByPage(
    ) {


        //描述信息检索
        ApplyInterfaceComplexVO complexPage = applyInterfaceInfoService.getComplexPage();

        return ResultUtils.success(complexPage);
    }

    /**
     * 表格详细信息
     * @param applyInterfaceInfoQuery
     * @return
     */
    @GetMapping("/list/page/detail_mes")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Page<ApplyInterfaceInfoVO>> listApplyInterfaceInfoMainMesByPage(
            ApplyInterfaceInfoQueryForAdminRequest applyInterfaceInfoQuery) {


        if (applyInterfaceInfoQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long size = applyInterfaceInfoQuery.getPageSize();

        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //描述信息检索
        Page<ApplyInterfaceInfoVO> mainMes = applyInterfaceInfoService.getMainMes(applyInterfaceInfoQuery);


        return ResultUtils.success(mainMes);
    }

    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/status")
    public BaseResponse<Boolean> updateApplyStatusAndAddUserInterface(
            ApplyInterfaceInfoUpdateRequest applyInterfaceInfoUpdateRequest) {

        if (applyInterfaceInfoUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = applyInterfaceInfoUpdateRequest.getId();
        new LambdaUpdateWrapper<ApplyInterfaceInfo>()
                .eq(ApplyInterfaceInfo::getId, id);
        ApplyInterfaceInfo applyInterfaceInfo = new ApplyInterfaceInfo();

        applyInterfaceInfo.setId(id);
        //前端传status 0 1 2
        Integer status = applyInterfaceInfoUpdateRequest.getStatus();
        applyInterfaceInfo.setStatus(status);
        applyInterfaceInfo.setUpdateTime(DateTime.now());
        try {


            boolean b = applyInterfaceInfoService.updateById(applyInterfaceInfo); //更新状态

            if(status==1) {
                //再根据id，查出userId,interfaceId
                ApplyInterfaceInfo byId = applyInterfaceInfoService.getById(id);
                Long userId = byId.getUserId();
                Long interfaceId = byId.getInterfaceId();

                //更新表格user_interface


                LambdaQueryWrapper<UserInterfaceInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserInterfaceInfo::getUserId, userId)
                        .eq(UserInterfaceInfo::getInterfaceId, interfaceId);

                // 查询是否存在记录
                UserInterfaceInfo existingRecord = userInterfaceInfoService.getOne(queryWrapper);

                if (existingRecord == null) {
                    // 如果不存在记录，则插入新记录
                    UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
                    userInterfaceInfo.setUserId(userId);
                    userInterfaceInfo.setInterfaceId(interfaceId);
                    userInterfaceInfo.setLeftNum(applyInterfaceInfoUpdateRequest.getApplyNum());
                    userInterfaceInfo.setTotalNum(applyInterfaceInfoUpdateRequest.getApplyNum());
                    userInterfaceInfoService.save(userInterfaceInfo);
                } else {
                    // 如果存在记录，则更新现有记录
                    UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
                    userInterfaceInfo.setInterfaceId(interfaceId);
                    userInterfaceInfo.setUserId(userId);
                    userInterfaceInfo.setLeftNum(existingRecord.getLeftNum() + applyInterfaceInfoUpdateRequest.getApplyNum());
                    userInterfaceInfo.setTotalNum(existingRecord.getTotalNum() + applyInterfaceInfoUpdateRequest.getApplyNum());
                    userInterfaceInfo.setUpdateTime(DateTime.now());
                    userInterfaceInfo.setId(existingRecord.getId());
                    userInterfaceInfoService.updateById(userInterfaceInfo);
                }
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(true);
    }


}
